
/**
 * 通过ID替换节点
 */
function   replaceNodeById(treeData, targetId, newData, idField = 'id') {
    if (!Array.isArray(treeData)) return false;

    for (let i = 0; i < treeData.length; i++) {
        const node = treeData[i];

        if (node[idField] === targetId) {
            treeData[i] = newData;
            // treeData[i] = typeof newData === 'function'
            //     ? newData(node)
            //     : { ...node, ...newData };
            return true;
        }

        if (node.children && Array.isArray(node.children)) {
            if (replaceNodeById(node.children, targetId, newData, idField)) {
                return true;
            }
        }
    }

    return false;
}

/**
 * 通过ID查找节点
 */
function findNodeById(treeData, targetId, idField = 'id') {
    if (!Array.isArray(treeData)) return null;

    for (const node of treeData) {
        if (node[idField] === targetId) {
            return node;
        }

        if (node.children && Array.isArray(node.children)) {
            const found = findNodeById(node.children, targetId, idField);
            if (found) return found;
        }
    }

    return null;
}

/**
 * 通过条件查找节点
 */
function findNode(treeData, predicate) {
    if (!Array.isArray(treeData)) return null;

    for (const node of treeData) {
        if (predicate(node)) {
            return node;
        }

        if (node.children && Array.isArray(node.children)) {
            const found = findNode(node.children, predicate);
            if (found) return found;
        }
    }

    return null;
}

export {replaceNodeById,findNode,findNodeById}
